﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using StoreTransport.DAO;
using StoreTransport.Business.Constants;
using StoreTransport.Business.Helper;
using StoreTransport.Resources;

namespace StoreTransport.Presentation.Forms {
    public partial class PermisstionListForm : Form {
        int id = 0;
        public PermisstionListForm() {
            InitializeComponent();
        }

        private void PermisstionListForm_Load(object sender, EventArgs e) {
            _tbxRoleName.Select();
            MDIMainForm main = (MDIMainForm)this.MdiParent;
            foreach (ToolStripMenuItem menu in main.MainMenuStrip.Items) {
                TreeNode node = new TreeNode(menu.Text);
                node.Name = menu.Name;
                node.Checked = true;
                foreach (ToolStripMenuItem submenu in menu.DropDownItems) {
                    node.Nodes.Add(submenu.Name, submenu.Text).Checked = true;
                }
                _ScreenTreeview.Nodes.Add(node);
            }
            _ScreenTreeview.ExpandAll();
            LoadRolesList();
        }

        private void LoadRolesList() { 
             _grdRoles.AutoGenerateColumns = false;
             _grdRoles.DataSource = CommonHelper.GetContext().Roles.Cast<Role>().OrderBy(c => c.RoleName);
        }

        private void _btxCreate_Click(object sender, EventArgs e) {
            id = 0;
            _tbxRoleName.Select();
            _tbxRoleName.Text = string.Empty;
            foreach (TreeNode node in _ScreenTreeview.Nodes) {
                CleanTreeViewNode(node);
            }
        }

        private void CleanTreeViewNode(TreeNode node) {
            node.Checked = false;
            if (node.Nodes.Count > 0) {
                foreach (TreeNode subnode in node.Nodes) {
                    CleanTreeViewNode(subnode);
                }
            }
        }

        private void _btxSave_Click(object sender, EventArgs e) {
            string selectedRole = string.Empty;
            string errorMessage = CommonHelper.CheckRequiredField(_tbxRoleName.Text, _lblRoleName.Text);
            if (!string.IsNullOrEmpty(errorMessage)) {
                MessageBox.Show(errorMessage);
                return;
            }
            foreach (TreeNode node in _ScreenTreeview.Nodes) {
                selectedRole += GetRoleTreeSelectedItems(node);
            }
            StoreTransportDataContext context = CommonHelper.GetContext();
            Role role = null;
            if (id == 0) {
                if (context.Users.FirstOrDefault(c => c.Username.Equals(_tbxRoleName.Text)) != null) {
                    MessageBox.Show(string.Format(StoreTransportResource.Error_Dupplicate_Role, _tbxRoleName.Text));
                    return;
                }
                role = new Role();
                context.Roles.InsertOnSubmit(role);
            } else {
                var item = context.Users.FirstOrDefault(c => c.Username.Equals(_tbxRoleName.Text));
                if (item != null && item.ID != id) {
                    MessageBox.Show(string.Format(StoreTransportResource.Error_Dupplicate_Role, _tbxRoleName.Text));
                    return;
                }
                role = context.Roles.Where(c => c.ID == id).First();
            }
            role.RoleName = _tbxRoleName.Text;
            role.Description = selectedRole;
            context.SubmitChanges();
            LoadRolesList();
        }
        private string GetRoleTreeSelectedItems(TreeNode node) {
            string selectedItems = string.Empty;
            if (node.Checked == true) {
                return node.Name + CommonConstant.ScreenSeparator;
            }
            foreach (TreeNode subnode in node.Nodes) {
                selectedItems += GetRoleTreeSelectedItems(subnode);
            }
            return selectedItems;
        }

        private void _btxEdit_Click(object sender, EventArgs e) {
            if (_grdRoles.SelectedRows.Count > 0) {
                id = int.Parse(_grdRoles.SelectedRows[0].Cells[0].Value.ToString());
                EditItem();
            }
        }

        private void EditItem() {
            Role selectedItem = CommonHelper.GetContext().Roles.Where(c => c.ID == id).First();
            _tbxRoleName.Text = selectedItem.RoleName;
            List<string> roles = selectedItem.Description.Split(new string[] { CommonConstant.ScreenSeparator },
                StringSplitOptions.RemoveEmptyEntries).ToList();
            foreach (TreeNode node in _ScreenTreeview.Nodes) {
                CleanTreeViewNode(node);
            }
            foreach (TreeNode node in _ScreenTreeview.Nodes) {
                BindRolesToTreeView(node, roles);
            }
        }
        private void BindRolesToTreeView(TreeNode node, List<string> roles) {
            if (roles.Contains(node.Name)) {
                node.Checked = true;
            }
            if (node.Nodes.Count > 0) {
                foreach (TreeNode subnode in node.Nodes) {
                    BindRolesToTreeView(subnode, roles);
                }
            }
        }

        private void _btnDelete_Click(object sender, EventArgs e) {
            if (_grdRoles.SelectedRows.Count > 0) {
                DialogResult result = MessageBox.Show(StoreTransportResource.Message_ConfirmDelete,
                    StoreTransportResource.MessageBox_ConfirmDelete, MessageBoxButtons.YesNo);
                if (result == System.Windows.Forms.DialogResult.Yes) {
                    try {
                        StoreTransportDataContext context = CommonHelper.GetContext();
                        foreach (DataGridViewRow row in _grdRoles.SelectedRows) {
                            id = int.Parse(row.Cells[0].Value.ToString());
                            Role selectedItem = context.Roles.Where(c => c.ID == id).First();
                            context.Roles.DeleteOnSubmit(selectedItem);
                            context.SubmitChanges();
                        }
                        LoadRolesList();
                        id = 0;
                    } catch (Exception ex) {
                        MessageBox.Show(StoreTransportResource.ErrorMessage_CanNotDeleteItem);
                    }
                }
            } else {
                MessageBox.Show(StoreTransportResource.NoItemSelected);
            }
        }

        private void _grdRoles_CellDoubleClick(object sender, DataGridViewCellEventArgs e) {
            id = int.Parse(_grdRoles.Rows[e.RowIndex].Cells[0].Value.ToString());
            EditItem();
        }
    }
}
